package com.medical.standard.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class ExcelExportUtil {

    /**
     * 导出数据到CSV格式（兼容Excel）
     */
    public static void exportToExcel(List<Map<String, Object>> dataList,
                                     String[] headers,
                                     String[] fieldNames,
                                     String fileName,
                                     HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");

        // 修复文件名编码 - 使用URL编码方式
        String encodedFileName = java.net.URLEncoder.encode(fileName + ".xls", "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        try (PrintWriter writer = response.getWriter()) {
            // 写入UTF-8 BOM，确保Excel正确显示中文
            writer.write("\uFEFF");

            // 写入表头
            writeCSVRow(writer, headers);

            // 写入数据行
            for (Map<String, Object> data : dataList) {
                String[] rowData = new String[fieldNames.length];
                for (int i = 0; i < fieldNames.length; i++) {
                    Object value = data.get(fieldNames[i]);
                    rowData[i] = formatCSVValue(value);
                }
                writeCSVRow(writer, rowData);
            }

            writer.flush();
        }
    }

    /**
     * 写入CSV行
     */
    private static void writeCSVRow(PrintWriter writer, String[] values) {
        if (values == null || values.length == 0) {
            writer.println();
            return;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(values[i]);
        }
        writer.println(sb.toString());
    }

    /**
     * 格式化CSV值（处理逗号、引号等特殊字符）
     */
    private static String formatCSVValue(Object value) {
        if (value == null) {
            return "";
        }

        String str = value.toString().trim();

        // 如果包含逗号、引号或换行符，需要用引号包围
        if (str.contains(",") || str.contains("\"") || str.contains("\n") || str.contains("\r")) {
            // 转义双引号
            str = str.replace("\"", "\"\"");
            return "\"" + str + "\"";
        }

        return str;
    }

    /**
     * 导出操作规程表 - 专门处理长文本
     */
    public static void exportProcedureTable(List<Map<String, Object>> dataList,
                                            String[] headers,
                                            String[] fieldNames,
                                            HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");

        // 修复：使用固定文件名，因为这个方法没有fileName参数
        String encodedFileName = java.net.URLEncoder.encode("操作规程表.xls", "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        try (PrintWriter writer = response.getWriter()) {
            // 写入UTF-8 BOM
            writer.write("\uFEFF");

            // 写入表头
            writeCSVRow(writer, headers);

            // 写入数据行
            for (Map<String, Object> data : dataList) {
                String[] rowData = new String[fieldNames.length];
                for (int i = 0; i < fieldNames.length; i++) {
                    Object value = data.get(fieldNames[i]);

                    // 特殊处理长文本字段，移除换行符
                    if (value != null && ("itemMethod".equals(fieldNames[i]) ||
                            "projectRequirement".equals(fieldNames[i]))) {
                        String text = value.toString();
                        // 将换行符替换为空格，避免破坏CSV格式
                        text = text.replace("\n", " ").replace("\r", " ");
                        rowData[i] = formatCSVValue(text);
                    } else {
                        rowData[i] = formatCSVValue(value);
                    }
                }
                writeCSVRow(writer, rowData);
            }

            writer.flush();
        }
    }
}